package com.neborosoft.lib.collections;

import java.util.Iterator;

/**
 * Created with IntelliJ IDEA.
 * User: CM
 * Date: 27.10.12
 * Time: 19:22
 * To change this template use File | Settings | File Templates.
 */
public class IterableConcat<T> implements Iterable<T>{

    private class ConcatIterator implements Iterator<T>{

        ConcatIterator(){
            position = -1;
            currentIterator = iterables[0].iterator();
        }

        private boolean toNextIterable(){
            position++;
            if(position == iterables.length){
                return false;
            }
            else{
                Iterable<T> iterable = iterables[position];
                if(iterable != null){
                    currentIterator = iterable.iterator();
                    return iterable.iterator().hasNext();
                }
                else{
                    return toNextIterable();
                }
            }
        }

        @Override
        public boolean hasNext() {
            if(currentIterator.hasNext()){
                return true;
            }
            else{
                return toNextIterable();
            }
        }

        @Override
        public T next() {
            return currentIterator.next();
        }

        @Override
        public void remove() {
            throw new UnsupportedOperationException("remove is not supported");
        }

        private int position;
        private Iterator<T> currentIterator;
    }

    @Override
    public Iterator<T> iterator() {
        return new ConcatIterator();
    }

    public Iterable<T>[] getIterables(){
        return iterables;
    }

    public IterableConcat(Iterable<T>... iterables){
        this.iterables = iterables;
    }

    private Iterable<T>[] iterables;
}
